package com.xiaoxin.smartbi.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel文件数据转csv工具
 */
public class ExcelUtils {
    public static String excelToCsv(MultipartFile multipartFile){
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(list.isEmpty()){
            return "";
        }
        StringBuilder dataBuilder=new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            LinkedHashMap<Integer,String> dataMap=(LinkedHashMap)list.get(i);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            String dataJoin = StringUtils.join(dataList, ",");
            dataBuilder.append(dataJoin).append("\n");
        }
        return dataBuilder.toString();
    }
}
